package com.example.sentinel.contorl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: ash
 * @time: 2024/2/8  23:13:20
 * @description:
 */
@RestController
@RequestMapping(value = "/test")
public class HelloWordController {

    @RequestMapping(value = "/sayHelloWorld.json")
    @SentinelResource(value = "sayHelloWorld",blockHandler = "exceptionHandler", fallback = "helloFallback")
    @ResponseBody
    public String sayHelloWorld(){

        System.out.println("sayHelloWorld!");
        return "helloWorld";
    }

    @RequestMapping(value = "/test.json")
    @ResponseBody
    public String test(){

        System.out.println("sayHelloWorld!");
        return "helloWorld";
    }


    @PostConstruct
    private static void initFlowRules(){
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("sayHelloWorld");
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // Set limit QPS to 20.
        rule.setCount(1);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }

    // Fallback 函数，函数签名与原函数一致或加一个 Throwable 类型的参数.
    public String helloFallback() {
        return String.format("Halooooo %d");
    }

    // Block 异常处理函数，参数最后多一个 BlockException，其余与原函数一致.
    public String exceptionHandler( BlockException ex) {
        // Do some log here.
        ex.printStackTrace();
        return "Oops, error occurred at ";
    }
}
